
import os
from app import create_app
from database import db
from models.user import User, Role, Permission, Device
from datetime import datetime
from flask_migrate import Migrate, upgrade

def init_db():
    app = create_app()
    migrate = Migrate(app, db)  # 初始化Flask-Migrate

    with app.app_context():
        # 初始化迁移仓库（如果不存在）
        migrations_dir = os.path.join(app.root_path, 'migrations')
        if not os.path.exists(migrations_dir):
            from flask_migrate import init
            init(directory=migrations_dir)
        
        # 应用所有迁移
        upgrade(directory=migrations_dir)
        
        # 检查是否已初始化（通过权限表判断）
        if Permission.query.count() > 0:
            print("数据库已初始化，跳过创建初始数据。")
            return
        
        # 创建权限
        permissions = [
            Permission(name='user_create', description='创建用户'),
            Permission(name='user_read', description='查看用户'),
            Permission(name='user_update', description='更新用户'),
            Permission(name='user_delete', description='删除用户'),
            Permission(name='role_manage', description='管理角色'),
            Permission(name='device_manage', description='管理设备'),
            Permission(name='dashboard_access', description='访问仪表盘')
        ]
        db.session.add_all(permissions)
        db.session.commit()

        # 创建角色
        admin_role = Role(name='admin', description='管理员角色')
        user_role = Role(name='user', description='普通用户角色')
        
        # 分配权限
        admin_role.permissions = permissions
        user_role.permissions = [
            p for p in permissions 
            if p.name in ['dashboard_access', 'user_read']
        ]
        db.session.add_all([admin_role, user_role])
        db.session.commit()
        
        # 创建管理员用户
        admin_user = User(
            username='admin',
            email='1195295423@qq.com',
            name='leon yan',
            is_active=True,
            created_at=datetime.utcnow()
        )
        admin_user.set_password(os.getenv('DEFAULT_ADMIN_PASSWORD', 'admin123'))
        admin_user.roles.append(admin_role)
        db.session.add(admin_user)
        db.session.commit()
        
        print("数据库初始化完成！")
        print("管理员账户：admin")
        print("请及时修改默认密码！")


if __name__ == '__main__':
    init_db()